package cn.stylefeng.guns.modular.tcpconnection;

import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.guns.modular.tcpconnection.entity.DeviceConnect;
import cn.stylefeng.guns.modular.tcpconnection.pojo.request.DeviceConnectRequest;
import cn.stylefeng.guns.modular.tcpconnection.service.DeviceConnectService;
import cn.stylefeng.guns.modular.tcpconnection.service.impl.DeviceConnectServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.util.zip.DeflaterInputStream;

public class TcpConnectionHandler implements Runnable {

    private final Socket clientSocket;
    private DeviceConnectServiceImpl deviceConnectService;

    public TcpConnectionHandler(Socket clientSocket, DeviceConnectServiceImpl deviceConnectService) {
        this.clientSocket = clientSocket;
        this.deviceConnectService = deviceConnectService;
    }

    @Override
    public void run() {
        try {
            System.out.println("Request accepted!");

            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            String request = in.readLine();
            System.out.println("Received message from client: " + request);

            String response = processRequest(request);

            out.println(response);
            System.out.println("Sent response to client: " + response);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String processRequest(String request) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            DeviceConnect deviceConnect = objectMapper.readValue(request, DeviceConnect.class);

            this.deviceConnectService.save(deviceConnect);

            String linkType = deviceConnect.getLinkType();
            String deviceIP = deviceConnect.getDeviceIp();
            String deviceName = deviceConnect.getDeviceName();
            String deviceType = deviceConnect.getDeviceType();
            String deviceStatus = deviceConnect.getDeviceStatus();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "Connection determined.";
    }
}
